package cn.edu.wfu.libautobook.controller;

import cn.edu.wfu.libautobook.bean.Result;
import cn.edu.wfu.libautobook.bean.User;
import cn.edu.wfu.libautobook.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;


    @GetMapping("/get")
    public Result getUser() {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        if (username == null) {
            return Result.fail("未认证用户信息");
        }
        User user = userService.getUserByUsername(username);
        user.setPassword(null);
        return Result.success(user);
    }

    @PostMapping("/register")
    public Result register(User user) {
        if (user.getUsername() == null || user.getPassword() == null || user.getPid() == null) {
            return Result.fail("参数不完全");
        }
        if (userService.getUserByUsername(user.getUsername()) != null) {
            return Result.fail("用户名被使用");
        }
        user.setRegisterTime(new Date());
        userService.register(user);
        return Result.success("注册成功");
    }

    @PostMapping("/login")
    public Result login(User user) {
        if (user.getUsername()==null || user.getPassword() == null) {
            return Result.fail("请输入用户名和密码");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken  =new UsernamePasswordToken(
                user.getUsername(),
                user.getPassword()
        );
        try {
            subject.login(usernamePasswordToken);
        }catch (UnknownAccountException e) {
            return Result.fail("用户不存在");
        }catch (AuthenticationException e) {
            return Result.fail("用户名或密码错误");
        }catch (Exception e) {
            return Result.fail("未知错误");
        }
        User u = userService.getUserByUsername(user.getUsername());
        u.setPassword(null);
        return Result.success(u);
    }

    @GetMapping("/logout")
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.success("");
    }

    @GetMapping("/401")
    public Result notAuth() {
        return Result.fail("未登陆, 请先登陆");
    }
}
